/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Engine2D.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;

/**
 *
 * @author Garys
 */
public class MulticastBroadcaster extends Thread {

    protected DatagramSocket socket = null;
    private InetAddress bcGroup = InetAddress.getByName("230.0.0.1");
    private int bcPort = 1908;
    
    
    protected String serverAddress = null;
    protected int serverPort;
    
    private long TWO_SECONDS = 2000;
    
    protected boolean broadcasting = true;


    public MulticastBroadcaster(String serverName, String serverAddress, int serverPort) throws IOException {
        super(serverName);
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;


        boolean attemptingCon = true;
        while (attemptingCon) {
            try {
                socket = new DatagramSocket(bcPort);
                attemptingCon = false;
                System.out.println(bcPort);
            } catch (SocketException e) {
                bcPort++;
            }
        }


    }

    public MulticastBroadcaster(String serverName, String serverAddress, int serverPort, String bcAddress, int bcPort) throws IOException {
        super(serverName);
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
        this.bcPort = bcPort;
        bcGroup = InetAddress.getByName(bcAddress);
        socket = new DatagramSocket(bcPort);
    }
    
    
    @Override
    public void run() {

        while (broadcasting) {
            try {
                byte[] buf = new byte[256];

                // construct quote
                String dString = null;

                dString = this.getName() + "," + serverAddress + "," + serverPort;
                buf = dString.getBytes();

                // send it

                DatagramPacket packet = new DatagramPacket(buf, buf.length, bcGroup, bcPort);
                socket.send(packet);

                // sleep for a while
                try {
                    sleep((long) (Math.random() * TWO_SECONDS));
                } catch (InterruptedException e) {
                }
            } catch (IOException e) {
                e.printStackTrace();
                broadcasting = false;
            }
        }
        socket.close();
    }
}